import os
import string
import operator
from docx import Document
import time
import win32com.client


def get_word_list(file_name):
    res = []
    if '.docx' in file_name:
        file = Document(file_name)
        for line in file.paragraphs:
            file2 = line.text.strip().replace(',', '').replace('.', '').split(' ')
            for item in file2:
                item2 = item.strip(string.punctuation)
                if len(item2) >= 1:
                    res.append(item)
    elif '.txt' in file_name:
        file = open(file_name, 'r').readlines()
        for line in file:
            file2 = line.strip().replace(',', '').replace('.', '').split(' ')
            for item in file2:
                item2 = item.strip(string.punctuation)
                if len(item2) >= 1:
                    res.append(item)
    elif '.doc' in file_name:
        file_name = doc2docx(file_name)
        file = Document(file_name)
        for line in file.paragraphs:
            file2 = line.text.strip().replace(',', '').replace('.', '').split(' ')
            for item in file2:
                item2 = item.strip(string.punctuation)
                if len(item2) >= 1:
                    res.append(item)
        os.remove(file_name)
    elif '.wps' in file_name:
        file_name = wps2docx(file_name)
        file = Document(file_name)
        for line in file.paragraphs:
            file2 = line.text.strip().replace(',', '').replace('.', '').split(' ')
            for item in file2:
                item2 = item.strip(string.punctuation)
                if len(item2) >= 1:
                    res.append(item)
        os.remove(file_name)
    result = {}
    for i in res:
        if i not in result:
            result[i] = 1
        else:
            result[i] += 1
    return result


def cut_word(k, word_list):
    word = sorted(word_list.items(), key=operator.itemgetter(1),reverse=True)
    result = word[:k]
    return result


def doc2docx(path):
    word = win32com.client.Dispatch('Word.Application')
    word.Visible = 0
    word.DisplayAlerts = 0
    doc = word.Documents.Open(path)
    newpath = os.path.splitext(path)[0] + 'new.docx'
    doc.SaveAs(newpath, 12, False, "", True, "", False, False, False, False)
    doc.Close()
    word.Quit()
    return newpath


def wps2docx(path):
    wps = win32com.client.Dispatch("Kwps.Application")  # 注意此处是Kwps, 并且注意大写。
    wps.Visible = 0
    wps.DisplayAlerts = 0
    mywps = wps.Documents.Open(path)
    newpath = os.path.splitext(path)[0] + 'new.docx'
    mywps.SaveAs(newpath, 12, False, "", True, "", False, False, False, False)
    mywps.Close()
    wps.Quit()
    return newpath


def main():
    k = 10
    file_name = 'file/1M.txt'

    time_start = time.perf_counter()
    word_list = get_word_list(file_name)
    time_end = time.perf_counter()
    time_sum = time_end - time_start  # 计算执行时间，单位为秒/s
    print("统计花费时间：" + str(round(time_sum, 4)) + "s")

    result = cut_word(k, word_list)
    print("出现频次最高的前10个单词：")
    for index in result:
        print(index)

    print("请输入要查询的单词（输入-1退出查询）：")
    word = input()
    while('-1' != word):
        try:
            print(word_list[word])
        except:
            print("没有这个单词，请重新查询")
        print("请输入要查询的单词（输入-1退出查询）：")
        word = input()


if __name__ == "__main__":
    main()

